package com.test.shiro.controller;

import com.test.shiro.domain.entity.UserInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @ClassName controller
 * @Author lulei
 * @Data 2020/3/1 16:16
 */

@RestController
public class Controller {

    private Logger logger= LoggerFactory.getLogger(Controller.class);


    @RequestMapping(value = "/toLogin")
    public Object toLogin() {

        return "login";
    }

    @RequestMapping(value = "/toIndex")
    public Object toIndex() {

        return "login";
    }


    /**
     * 登陆的方法
     * @return string
     */
    @RequestMapping(value = "/login")
    public String login(UserInfo user, Model model) {
        //封装成请求对象
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), user.getPassword());
        //获取登陆的主体对象
        Subject subject = SecurityUtils.getSubject();
        //登陆
        try{

            subject.login(token);
        }catch (UnknownAccountException err) {

            //用户名不对
            logger.error("用户名不对");
            model.addAttribute("userNameError","用户名不对");
            return "login";
        }catch (IncorrectCredentialsException err) {

            //说明是密码不对
            logger.error("密码不对");
            model.addAttribute("passwordError","密码不对");
            return "login";
        }catch (Exception err) {
            logger.error("其他问题造成登陆失败:"+err.fillInStackTrace());
            model.addAttribute("otherError","其他问题造成登陆失败");
            return "login";
        }
        return "index";
    }
}
